﻿var items;

$(document).ready(function () {

    if (window.location.href.indexOf("?selectedItem=myTeams") < 0 && window.location.href.indexOf("?selectedItem=allUsers") < 0) {
        window.location.href = "Users.aspx?selectedItem=allUsers";
    }
    if (window.location.href.indexOf("?selectedItem=myTeams") >= 0) {
        $("#myTeams a").css({ 'color': '#8EBD00' });
        $(".hTxt").text("Users > My Teams");
        if ($.cookie("userS") == "Admin") {
            getAllTeams($.cookie("userId"));
        } else {
            getAllMyTeams($.cookie("userId"));
        }
    }
    else if (window.location.href.indexOf("?selectedItem=allUsers") >= 0) {
        $("#usersSubmenu a").css({ 'color': '#8EBD00' });
        $(".hTxt").text("Users > All Users");
        getAllUsers();
    }

    $('#addUserBtn1, #addUserBtn2').click(function () {
        $('#addBtn').button('reset').css({ 'background': '' });
        setValuesAddUserPop("", "", "", "", "", "Admin", "", "");
        $('#addUserPopHeadTxt').text("Add New User");
        $('body').css({ 'position': 'fixed', 'width': '100%' });
        $('#addUserPop, #usersOverlay, #addBtn').show();
    });

    $('#closeAddUserPop').click(function() {
        $('body').css({ 'position': '', 'width': '100%' });
        $('#addUserPop, #usersOverlay, #addBtn, #editBtn').hide();
        $("#loginBox").removeAttr("readonly");
    });

    $('#closeRemovePop, #cancelRemovePopBtn').click(function() {
        $('#userId').val('');
        $('body').css({ 'position': '', 'width': '100%' });
        $('#removePop, #usersOverlay').hide();
    });

    $('#removeBtn').click(function () {
        $('#removeBtn, #cancelRemovePopBtn').button('loading');
        $('#removeBtn').css({ 'background': '#6a7b42' });
        removeUser($.cookie('userId'), $('#userId').val());
    });

    $('#addBtn').click(function () {
        if (validateFields()) {
            $('#addBtn').button('loading').css({ 'background': '#6a7b42' });
            addUser($("#nameBox").val(), $("#snameBox").val(), $("#patronymicBox").val(),
                $("#emailBox").val(), $("#loginBox").val(), $("#passwordBox").val(),
                $('#roles').find(":selected").text(), $.cookie("userId"));
        }
    });

    $('#editBtn').click(function () {
        if (validateFields()) {
            $('#editBtn').button('loading').css({ 'background': '#6a7b42' });;
            editUser($.cookie("userId"), $('#userIdToEdit').val(), $("#nameBox").val(),
                $("#snameBox").val(), $("#patronymicBox").val(), $("#emailBox").val(),
                $("#passwordBox").val(), $('#roles').find(":selected").text());
        }
    });

    $("#userSelection").change(function() {
        var status = $('#userSelection').find(":selected").text();
        $(".td").remove();
        if ( status == "All Users") {
            drawItems();
        } else {
            var selectedItems = [];
            for (var i = 0; i < items.length; i++) {
                if (items[i].Status == status) {
                    selectedItems.push(items[i]);
                }
            }
            for (i = 0; i < selectedItems.length; i++) {
                DrawUser(selectedItems[i], i);
            }
        }
    });

    $("#teamSelection").change(function() {
        var status = $('#teamSelection').find(":selected").text();
        $("#myTeamsContents").empty();
        if (status == "All Teams") {
            drawAllTeams();
        } else {
            drawMyTeams();
        }
    });
});

function setValuesAddUserPop(name, surname, phone, email, login, role, password, cpassword) {
    $("#nameBox").val(name).css({ 'background': 'url("/Resources/img/input.png") no-repeat' });;
    $("#snameBox").val(surname).css({ 'background': 'url("/Resources/img/input.png") no-repeat' });;
    $("#patronymicBox").val(phone).css({ 'background': 'url("/Resources/img/input.png") no-repeat' });;
    $("#emailBox").val(email).css({ 'background': 'url("/Resources/img/input.png") no-repeat' });;
    $("#loginBox").val(login).css({ 'background': 'url("/Resources/img/input.png") no-repeat' });;
    if (role != "") {
        $("#roles option").each(function () {
            if ($(this).text() == role) {
                $(this).attr("selected", "selected");
            }
        });
    }
    $("#passwordBox").val(password).css({ 'background': 'url("/Resources/img/input.png") no-repeat' });;
    $("#cpasswordBox").val(cpassword).css({ 'background': 'url("/Resources/img/input.png") no-repeat' });;
}

function editUserIconClick(id) {
    $('#editBtn').button('reset').css({ 'background': '' });
    var userIndex = searchUser(id);
    if (userIndex != -1) {
        setValuesAddUserPop(items[userIndex].Name, items[userIndex].Surname,
            items[userIndex].Phone, items[userIndex].Email,
            items[userIndex].Login, items[userIndex].Status, "", "");
        $('#userIdToEdit').val(items[userIndex].Id);
        $("#loginBox").attr("readonly", "readonly");
    }
    $('#addUserPopHeadTxt').text("Edit User");
    $('body').css({ 'position': 'fixed', 'width': '100%' });
    $('#addUserPop, #usersOverlay, #editBtn').show();
}

function removeUserIconClick(id, login) {
    $('#removeBtn, #cancelRemovePopBtn').button('reset');
    $('#removeBtn').css({ 'background': '' });
    $('#removeTxt').text("Are you sure you want to delete '" + login + "' from the system?");
    $('#userId').val(id);
    $('body').css({ 'position': 'fixed', 'width': '100%' });
    $('#removePop, #usersOverlay').show();
}

function successShowUsers(data) {
    if (!showError(data))
        return;
    items = $.parseJSON(data.Message);
    drawItems();
}

function drawItems() {
    for (var i = 0; i < items.length; i++) {
        DrawUser(items[i], i);
    }
}

function DrawUser(item, number) {
    $('<tr/>', {
        id: 'tr-' + number,
        class: "td " + (((number + 1) % 2) ? "" : "odd")
    }).appendTo('#userTable');

    $('<td/>', {
        id: 'tdNumber-' + number,
        text: number + 1
    }).appendTo('#tr-' + number).css({ 'text-align': 'center' });

    $('<td/>', {
        id: 'tdName-' + number,
        text: item.Name
    }).appendTo('#tr-' + number);

    $('<td/>', {
        id: 'tdSname-' + number,
        text: item.Surname
    }).appendTo('#tr-' + number);

    $('<td/>', {
        id: 'tdPatronymic-' + number,
        text: item.Phone
    }).appendTo('#tr-' + number);

    $('<td/>', {
        id: 'tdEmail-' + number,
        text: item.Email
    }).appendTo('#tr-' + number);

    $('<td/>', {
        id: 'tdLogin-' + number,
        text: item.Login
    }).appendTo('#tr-' + number);

    $('<td/>', {
        id: 'tdRole-' + number,
        text: item.Status
    }).appendTo('#tr-' + number);

    $('<td/>', {
        id: 'tdEdit-' + number
    }).appendTo('#tr-' + number).css({ 'width': '50px' });

    $('<div/>', {
        id: 'edit-' + number,
        class: "editIcon",
        onclick: "editUserIconClick('" + item.Id + "');"
    }).appendTo('#tdEdit-' + number);

    $('<td/>', {
        id: 'tdRemove-' + number
    }).appendTo('#tr-' + number).css({ 'width': '50px' });

    $('<div/>', {
        id: 'edit-' + number,
        class: "removeIcon",
        onclick: "removeUserIconClick('" + item.Id + "', '" + item.Login + "');"
    }).appendTo('#tdRemove-' + number);

}

function successAddUser(data) {
    if (!showError(data)) {
        $('#addBtn').button('reset').css({ 'background': '' });;
        return;
    }
    $('#closeAddUserPop').click();
    var newUser = $.parseJSON(data.Message);
    items.push(newUser);
    $("#userSelection").change();
}

function successEditUser(data) {
    if (!showError(data)) {
        $('#editBtn').button('reset').css({ 'background': '' });;
        return;
    }
    var index = searchUser($('#userIdToEdit').val());
    if (index != -1) {
        items[index].Name = $("#nameBox").val();
        items[index].Surname = $("#snameBox").val();
        items[index].Phone = $("#patronymicBox").val();
        items[index].Email = $("#emailBox").val();
        items[index].Status = $('#roles').find(":selected").text();
    }
    $("#userSelection").change();
    $('#closeAddUserPop').click();
    $('#userIdToEdit').val("");
}

function successRemoveUser(data, id) {
    if (!showError(data)) {
        $('#removeBtn, #cancelRemovePopBtn').button('reset');
        $('#removeBtn').css({ 'background': '' });
        return;
    }
    var index = searchUser(id);
    if (index != -1) {
        items.splice(index, 1);
        $("#userSelection").change();
        $('#closeRemovePop').click();
    }
}

function showError(data) {
    if (data.Status == "error") {
        showExceptionPop("Error", data.Message);
        return false;
    }
    else if (data.Status == "server_error") {
        showExceptionPop("Server Error", "Server error. Please try again later.");
        return false;
    }
    return true;
}

function searchUser(id) {
    for (var i = 0; i < items.length; i++) {
        if (items[i].Id == id) {
            return i;
        }
    }
    return -1;
}

function validateFields() {
    var name = $('#nameBox');
    var sname = $('#snameBox');
    var phone = $('#patronymicBox');
    var login = $('#loginBox');
    var password = $('#passwordBox');
    var cpassword = $('#cpasswordBox');
    var email = $('#emailBox');
    var flag = true;
    if (!validateName(name, sname, phone))
        flag = false;
    if (!validateEmail(email))
        flag = false;
    if (!validateName(login, password, cpassword))
        flag = false;
    if (!passwordsCorrespond(password, cpassword)) {
        flag = false;
    }
    return flag;
}

function passwordsCorrespond(pass, cpass) {
    if (pass.val() != cpass.val()) {
        pass.css({ 'background': 'url("/Resources/img/inputErr.png") no-repeat' });
        cpass.css({ 'background': 'url("/Resources/img/inputErr.png") no-repeat' });
        return false;
    }
    return true;
}

function validateName(selector1, selector2, selector3) {
    var flag = true;
    var regex = new RegExp("^ +$");
    if (selector1.val() == "" || regex.test(selector1.val())) {
        flag = false;
        selector1.css({ 'background': 'url("/Resources/img/inputErr.png") no-repeat' });
    } else {
        selector1.css({ 'background': 'url("/Resources/img/input.png") no-repeat' });
    }
    if (selector2.val() == "" || regex.test(selector2.val())) {
        flag = false;
        selector2.css({ 'background': 'url("/Resources/img/inputErr.png") no-repeat' });
    } else {
        selector2.css({ 'background': 'url("/Resources/img/input.png") no-repeat' });
    }
    if (selector3.val() == "" || regex.test(selector3.val())) {
        flag = false;
        selector3.css({ 'background': 'url("/Resources/img/inputErr.png") no-repeat' });
    } else {
        selector3.css({ 'background': 'url("/Resources/img/input.png") no-repeat' });
    }
    return flag;
}

function validateEmail(selector) {
    var regex = new RegExp("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$");
    if (regex.test(selector.val()) && selector.val() != "") {
        selector.css({ 'background': 'url("/Resources/img/input.png") no-repeat' });
        return true;
    } else {
        selector.css({ 'background': 'url("/Resources/img/inputErr.png") no-repeat' });
        return false;
    }
}

/*------------------------------------------- My Teams -----------------------------------------------*/

var teams;

function successShowMyTeams(data) {
    if (!showError(data))
        return;
    teams = $.parseJSON(data.Message);
    if (teams.length == 0) {
        $("<div/>", {
            id: "noTeams",
        }).appendTo("#myTeamsContents").text(noTeams);
        if ($.cookie("userS")=="Admin") {
            $("#teamSelection, #selectTeamsText").hide();
        }
    } else {
        drawAllTeams();
    }
}

function drawAllTeams() {
    for (var i = 0; i < teams.length; i++) {
        drawTeam(i, teams[i]);
    }
}

function drawMyTeams() {
    var myTeams=[];
    for (var i = 0; i < teams.length; i++) {
        for (var j = 0; j < teams[i].TeamMembers.length; j++) {
            if (teams[i].TeamMembers[j].Id == $.cookie("userId")) {
                myTeams.push(teams[i]);
                continue;
            }
        }
    }
    if (myTeams.length == 0) {
        $("<div/>", {
            id: "noTeams",
        }).appendTo("#myTeamsContents").text(noTeams);
    } else {
        for (i = 0; i < myTeams.length; i++) {
            drawTeam(i, myTeams[i]);
        }
    }
}

function drawTeam(number, team) {
    $("<div/>", {
        id: "team-" + number
    }).appendTo("#myTeamsContents");

    $("<div/>", {
        id: "goalName-" + number,
        class: "goalName"
    }).appendTo("#team-" + number).text(team.GoalName);

    if (team.TeamMembers.length != 0) {

        $("<table/>", {
            id: "teamTable-" + number,
            class: "teamTable"
        }).appendTo("#team-" + number);

        $("#teamTable-" + number).attr("cellspacing", "0");

        initMyTeamTableHeader("#teamTable-" + number, number);
        initUsers("#teamTable-" + number, team.TeamMembers, number);
    } else {
        $("<div/>", {
            id: "noUserInTeam-" + number,
            class: "noUserInTeam"
        }).appendTo("#team-" + number).text(noUserInTeam);
    }

    $("<div/>", {
        id: "teamLine-" + number,
        class: "teamLine"
    }).appendTo("#team-" + number);
}

function initMyTeamTableHeader(id, number) {
    $("<tr/>", {
        class: "teamTableHeader",
        id: "teamTableHeader"+number
    }).appendTo(id);

    $("<th/>", {
        class: "numberTable"
    }).appendTo("#teamTableHeader" + number).text(numberTable);

    $("<th/>", {
        class: "nameTable"
    }).appendTo("#teamTableHeader" + number).text(nameTable);

    $("<th/>", {
        class: "surnameTable"
    }).appendTo("#teamTableHeader" + number).text(surnameTable);

    $("<th/>", {
        class: "phoneTable"
    }).appendTo("#teamTableHeader" + number).text(phoneTable);

    $("<th/>", {
        class: "emailTable"
    }).appendTo("#teamTableHeader" + number).text(emailTable);

    $("<th/>", {
        class: "loginTable"
    }).appendTo("#teamTableHeader" + number).text(loginTable);

    $("<th/>", {
        class: "roleTable"
    }).appendTo("#teamTableHeader" + number).text(roleTable);
}

function initUsers(id, teamMembers, number) {
    for (var i = 0; i < teamMembers.length; i++) {
        $("<tr/>", {
            class: "td " + (((i + 1) % 2) ? "" : "odd"),
            id: "teamTable-" + number + "-" + i
        }).appendTo(id);
        $("<td/>").appendTo("#teamTable-" + number + "-" + i).text(i + 1).css({ 'text-align': 'center' });
        $("<td/>").appendTo("#teamTable-" + number + "-" + i).text(teamMembers[i].Name);
        $("<td/>").appendTo("#teamTable-" + number + "-" + i).text(teamMembers[i].Surname);
        $("<td/>").appendTo("#teamTable-" + number + "-" + i).text(teamMembers[i].Phone);
        $("<td/>").appendTo("#teamTable-" + number + "-" + i).text(teamMembers[i].Email);
        $("<td/>").appendTo("#teamTable-" + number + "-" + i).text(teamMembers[i].Login);
        $("<td/>").appendTo("#teamTable-" + number + "-" + i).text(teamMembers[i].Status);
    }
}